package com.tt.ProxyFactory.cglib;

import com.tt.TransactionController.TransactionController;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibTransactionProxy implements MethodInterceptor {

    private final Object target;
    private final TransactionController transactionController;

    public CglibTransactionProxy(Object target, TransactionController transactionController) {
        this.target = target;
        this.transactionController = transactionController;
    }

    public Object getProxyInstance() {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        Object result = null;
        try {
            transactionController.beginTransaction();
            result = proxy.invokeSuper(obj, args);
            transactionController.commit();
        } catch (Exception e) {
            transactionController.rollback();
            throw e;
        }
        return result;
    }
}
